package com.shitou.springai1.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shitou.springai1.admin.entity.dto.UserDto;
import com.shitou.springai1.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户管理控制器
 * 处理用户相关的API请求
 */
@RestController
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping("/api/admin/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 定义用户头像存储路径
    private static final String USER_IMAGE_PATH = "src/main/resources/imagesUser/";
    private static final String USER_IMAGE_BASE_URL = "/static/imagesUser/";

    /**
     * 保存用户头像文件
     * 将Base64格式的图片数据转换为文件并保存到指定目录
     * @param base64Image Base64格式的图片数据
     * @return 保存后的图片URL路径
     */
    private String saveUserAvatar(String base64Image) {
        if (base64Image == null || base64Image.isEmpty()) {
            return null;
        }

        try {
            // 确保存储目录存在
            File directory = new File(USER_IMAGE_PATH);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 解析Base64图片数据
            String[] parts = base64Image.split(",");
            String imageData = parts[parts.length > 1 ? 1 : 0];
            byte[] imageBytes = Base64.getDecoder().decode(imageData);

            // 获取图片格式
            String format;
            if (base64Image.startsWith("data:image/jpeg")) {
                format = "jpeg";
            } else if (base64Image.startsWith("data:image/png")) {
                format = "png";
            } else if (base64Image.startsWith("data:image/gif")) {
                format = "gif";
            } else {
                // 默认使用jpg格式
                format = "jpg";
            }

            // 生成唯一文件名：使用UUID + 时间戳 + 扩展名
            String timestamp = String.valueOf(System.currentTimeMillis());
            String randomId = UUID.randomUUID().toString().substring(0, 8);
            String fileName = "avatar_" + timestamp + "_" + randomId + "." + format;
            String filePath = USER_IMAGE_PATH + fileName;

            // 保存文件
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                fos.write(imageBytes);
            }

            // 返回图片URL路径
            return USER_IMAGE_BASE_URL + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取用户列表（分页查询）
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @param keyword 搜索关键词（昵称或学号/工号）
     * @param status 账号状态筛选
     * @return 分页用户数据
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {
        try {
            // 创建分页对象
            Page<UserDto> page = new Page<>(pageNum, pageSize);

            // 构建查询条件
            Page<UserDto> userPage = userService.page(page, new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserDto>()
                    .and(keyword != null && !keyword.isEmpty(), w -> w
                            .like("nick_name", keyword)
                            .or().like("stu_or_tea_id", keyword)
                    )
                    .eq(status != null, "account_status", status)
                    .orderByDesc("register_time")
            );

            // 构建返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("records", userPage.getRecords());
            response.put("total", userPage.getTotal());
            response.put("size", userPage.getSize());
            response.put("current", userPage.getCurrent());
            response.put("pages", userPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "获取用户列表失败：" + e.getMessage()));
        }
    }

    /**
     * 获取单个用户详情
     * @param id 用户ID
     * @return 用户详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        try {
            UserDto user = userService.getById(id);
            if (user == null) {
                return ResponseEntity.status(404).body(Map.of("error", "用户不存在"));
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "获取用户详情失败：" + e.getMessage()));
        }
    }

    /**
     * 添加新用户
     * @param userDto 用户信息
     * @return 添加结果
     */
    @PostMapping
    public ResponseEntity<?> addUser(@RequestBody UserDto userDto) {
        try {
            // 检查必要字段
            if (userDto.getNickName() == null || userDto.getNickName().isEmpty() ||
                userDto.getStuOrTeaId() == null || userDto.getStuOrTeaId().isEmpty() ||
                userDto.getUserPass() == null || userDto.getUserPass().isEmpty()) {
                return ResponseEntity.status(400).body(Map.of("error", "昵称、学号/工号和密码不能为空"));
            }

            // 检查学号/工号是否已存在
            if (userService.count(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserDto>()
                    .eq("stu_or_tea_id", userDto.getStuOrTeaId())) > 0) {
                return ResponseEntity.status(400).body(Map.of("error", "该学号/工号已被使用"));
            }

            // 设置默认值
            if (userDto.getAccountStatus() == null) {
                userDto.setAccountStatus(0); // 0: 正常
            }

            if (userDto.getRole() == null) {
                userDto.setRole("USER"); // 默认普通用户角色
            }

            // 处理用户头像：如果是Base64数据，则保存为文件并更新路径
            if (userDto.getImageUrl() != null && userDto.getImageUrl().startsWith("data:image/")) {
                String imagePath = saveUserAvatar(userDto.getImageUrl());
                userDto.setImageUrl(imagePath);
            }

            // 生成唯一的用户系统ID
            String userId = "USER_" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            userDto.setUserId(userId);

            // 保存用户前，确保id为null，使用数据库自增机制
            userDto.setId(null);
            boolean saved = userService.save(userDto);
            if (saved) {
                return ResponseEntity.ok(Map.of("success", true, "message", "用户添加成功"));
            } else {
                return ResponseEntity.status(500).body(Map.of("error", "用户添加失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "添加用户失败：" + e.getMessage()));
        }
    }

    /**
     * 更新用户信息
     * @param id 用户ID
     * @param userDto 更新的用户信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody UserDto userDto) {
        try {
            // 检查用户是否存在
            if (!userService.lambdaQuery().eq(UserDto::getId, id).exists()) {
                return ResponseEntity.status(404).body(Map.of("error", "用户不存在"));
            }

            // 设置用户ID，确保更新的是指定用户
            userDto.setId(id);

            // 如果修改了学号/工号，检查新学号/工号是否已存在
            if (userDto.getStuOrTeaId() != null && !userDto.getStuOrTeaId().isEmpty()) {
                UserDto existingUser = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserDto>()
                        .eq("stu_or_tea_id", userDto.getStuOrTeaId())
                        .ne("id", id)
                );
                if (existingUser != null) {
                    return ResponseEntity.status(400).body(Map.of("error", "该学号/工号已被使用"));
                }
            }

            // 处理用户头像：如果是Base64数据，则保存为文件并更新路径
            if (userDto.getImageUrl() != null && userDto.getImageUrl().startsWith("data:image/")) {
                String imagePath = saveUserAvatar(userDto.getImageUrl());
                userDto.setImageUrl(imagePath);
            }

            // 更新用户
            boolean updated = userService.updateById(userDto);
            if (updated) {
                return ResponseEntity.ok(Map.of("success", true, "message", "用户更新成功"));
            } else {
                return ResponseEntity.status(500).body(Map.of("error", "用户更新失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "更新用户失败：" + e.getMessage()));
        }
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        try {
            // 检查用户是否存在
            if (!userService.lambdaQuery().eq(UserDto::getId, id).exists()) {
                return ResponseEntity.status(404).body(Map.of("error", "用户不存在"));
            }

            // 删除用户
            boolean deleted = userService.removeById(id);
            if (deleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "用户删除成功"));
            } else {
                return ResponseEntity.status(500).body(Map.of("error", "用户删除失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "删除用户失败：" + e.getMessage()));
        }
    }

    /**
     * 批量删除用户
     * @param ids 用户ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteUsers(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return ResponseEntity.status(400).body(Map.of("error", "请选择要删除的用户"));
            }

            // 检查用户是否存在
            long count = userService.count(new LambdaQueryWrapper<UserDto>().in(UserDto::getId, ids));
            if (count < ids.size()) {
                return ResponseEntity.status(400).body(Map.of("error", "部分用户不存在，请刷新列表后重试"));
            }

            // 批量删除用户
            boolean deleted = userService.removeByIds(ids);
            if (deleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "用户批量删除成功"));
            } else {
                return ResponseEntity.status(500).body(Map.of("error", "用户批量删除失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "批量删除用户失败：" + e.getMessage()));
        }
    }

    /**
     * 启用/禁用用户账号
     * @param id 用户ID
     * @param status 账号状态（0：正常，1：禁用）
     * @return 操作结果
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateUserStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            // 检查用户是否存在
            if (!userService.lambdaQuery().eq(UserDto::getId, id).exists()) {
                return ResponseEntity.status(404).body(Map.of("error", "用户不存在"));
            }

            // 检查状态值是否合法
            if (status != 0 && status != 1) {
                return ResponseEntity.status(400).body(Map.of("error", "状态值必须是0或1"));
            }

            // 更新用户状态
            UserDto userDto = new UserDto();
            userDto.setId(id);
            userDto.setAccountStatus(status);
            boolean updated = userService.updateById(userDto);
            if (updated) {
                String message = status == 0 ? "用户账号已启用" : "用户账号已禁用";
                return ResponseEntity.ok(Map.of("success", true, "message", message));
            } else {
                return ResponseEntity.status(500).body(Map.of("error", "更新用户状态失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "更新用户状态失败：" + e.getMessage()));
        }
    }

    /**
     * 修改用户密码
     * @param id 用户ID
     * @param passwordInfo 包含旧密码和新密码的信息
     * @return 修改结果
     */
    @PutMapping("/{id}/password")
    public ResponseEntity<?> updateUserPassword(@PathVariable Long id, @RequestBody Map<String, String> passwordInfo) {
        try {
            // 检查用户是否存在
            UserDto user = userService.getById(id);
            if (user == null) {
                return ResponseEntity.status(404).body(Map.of("error", "用户不存在"));
            }

            // 获取请求参数
            String newPassword = passwordInfo.get("newPassword");

            // 检查密码是否为空
            if (newPassword == null || newPassword.isEmpty()) {
                return ResponseEntity.status(400).body(Map.of("error", "新密码不能为空"));
            }

            // 检查密码长度
            if (newPassword.length() < 6) {
                return ResponseEntity.status(400).body(Map.of("error", "密码长度不能少于6位"));
            }

            // 更新密码
            UserDto updateUser = new UserDto();
            updateUser.setId(id);
            updateUser.setUserPass(newPassword); // 假设密码在service层会被加密
            boolean updated = userService.updateById(updateUser);
            if (updated) {
                return ResponseEntity.ok(Map.of("success", true, "message", "密码修改成功"));
            } else {
                return ResponseEntity.status(500).body(Map.of("error", "密码修改失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "修改密码失败：" + e.getMessage()));
        }
    }

    /**
     * 搜索用户（高级搜索）
     * @param searchParams 搜索参数
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 搜索结果
     */
    @PostMapping("/search")
    public ResponseEntity<Map<String, Object>> searchUsers(
            @RequestBody Map<String, Object> searchParams,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            // 创建分页对象
            Page<UserDto> page = new Page<>(pageNum, pageSize);

            // 构建查询条件
            QueryWrapper<UserDto> queryWrapper = new QueryWrapper<>();

            // 昵称搜索
            if (searchParams.containsKey("nickName") && searchParams.get("nickName") != null) {
                queryWrapper.like("nick_name", searchParams.get("nickName"));
            }

            // 学号/工号搜索
            if (searchParams.containsKey("stuOrTeaId") && searchParams.get("stuOrTeaId") != null) {
                queryWrapper.like("stu_or_tea_id", searchParams.get("stuOrTeaId"));
            }

            // 角色搜索
            if (searchParams.containsKey("role") && searchParams.get("role") != null) {
                queryWrapper.eq("role", searchParams.get("role"));
            }

            // 账号状态搜索
            if (searchParams.containsKey("accountStatus") && searchParams.get("accountStatus") != null) {
                queryWrapper.eq("account_status", searchParams.get("accountStatus"));
            }

            // 按注册时间排序
            queryWrapper.orderByDesc("register_time");

            // 执行查询
            Page<UserDto> userPage = userService.page(page, queryWrapper);

            // 构建返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("records", userPage.getRecords());
            response.put("total", userPage.getTotal());
            response.put("size", userPage.getSize());
            response.put("current", userPage.getCurrent());
            response.put("pages", userPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of("error", "搜索用户失败：" + e.getMessage()));
        }
    }
}
